package win.wellcoding.wechat.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;

import com.opensymphony.xwork2.ActionSupport;

import win.wellcoding.wechat.give.GiveXmlProcess;
import win.wellcoding.wechat.receive.ReceiveXmlEntity;
import win.wellcoding.wechat.receive.ReceiveXmlProcess;
import win.wellcoding.wechat.tuling.TulingApiProcess;

@Scope("prototype")
@ParentPackage(value = "struts-authentication")
public class MainAction extends AbstractCommonAction {
	
	private static Logger logger 		= Logger.getLogger(MainAction.class);

	@Action("reply")
	public void reply() throws IOException {
		logger.info("接收请求...");
		/** 读取接收到的xml消息 */
		StringBuffer sb = new StringBuffer();
		InputStream is = request.getInputStream();
		InputStreamReader isr = new InputStreamReader(is, "UTF-8");
		BufferedReader br = new BufferedReader(isr);
		String s = "";
		while ((s = br.readLine()) != null) {
			sb.append(s);
		}
		String xml = sb.toString(); // 次即为接收到微信端发送过来的xml数据
		
		logger.info(xml);

		String result = "";
		/** 判断是否是微信接入激活验证，只有首次接入验证时才会收到echostr参数，此时需要把它直接返回 */
		String echostr = request.getParameter("echostr");
		if (echostr != null && echostr.length() > 1) {
			result = echostr;
		} else {
			// 正常的微信处理流程
			/** 解析xml数据 */  
	        ReceiveXmlEntity xmlEntity = ReceiveXmlProcess.getMsgEntity(xml);  
	          
	        /** 以文本消息为例，调用图灵机器人api接口，获取回复内容 */  
	        if(xmlEntity!=null&&"text".endsWith(xmlEntity.getMsgType())){  
	            result = new TulingApiProcess().getTulingResult(xmlEntity.getContent());  
	        }  
	          
	        /** 此时，如果用户输入的是“你好”，在经过上面的过程之后，result为“你也好”类似的内容  
	         *  因为最终回复给微信的也是xml格式的数据，所有需要将其封装为文本类型返回消息 
	         * */  
	        result = GiveXmlProcess.getTextXmlAnswer(xmlEntity.getFromUserName(), xmlEntity.getToUserName(), result);  
//			result = new WechatProcess().processWechatMag(xml);
		}

		try {
			OutputStream os = response.getOutputStream();
			os.write(result.getBytes("UTF-8"));
			os.flush();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Action(value="jssdk",results={@Result(name="jssdk",location="/WEB-INF/jssdk.jsp")})
	public String jssdk(){
		return "jssdk";
	}
}
